package com.apache.poi.word.config.policy;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.policy.RenderPolicy;
import com.deepoove.poi.template.ElementTemplate;
import com.deepoove.poi.template.run.RunTemplate;
import com.deepoove.poi.util.ReflectionUtils;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * @Author: HUANG GY.
 * @Date: 2022/2/14 16:34
 * @Description: 生成表格插件
 */
public class TableRenderPolicy  implements RenderPolicy {


    @Override
    public void render(ElementTemplate eleTemplate, Object data, XWPFTemplate template) {
        RunTemplate runTemplate = (RunTemplate) eleTemplate;
        XWPFRun run = runTemplate.getRun();
        XWPFParagraph paragraph = run.getParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        paragraph.setVerticalAlignment(TextAlignment.CENTER);
        XWPFDocument doc = run.getParent().getDocument();
        List<Map<String,String>> rowMapList = (List<Map<String,String>>)data;
        XWPFTable table = doc.createTable(rowMapList.size(), rowMapList.get(0).size());
        //表格居中
        CTTbl ttbl = table.getCTTbl();
        CTTblPr tblPr = ttbl.addNewTblPr();
        tblPr.addNewJc().setVal(org.openxmlformats.schemas.wordprocessingml.x2006.main.STJcTable.Enum.forInt(1));
        CTTblGrid tblGrid = ttbl.getTblGrid() != null ? ttbl.getTblGrid() : ttbl.addNewTblGrid();
        CTTblGridCol gridCol = tblGrid.addNewGridCol();
        for (int j = 0; j < rowMapList.get(0).size(); j++){
            gridCol.setW(new BigInteger("20"));
        }
        for (int i = 0; i < rowMapList.size(); i++) {
            Map<String, String> row = rowMapList.get(i);
            Set<String> set = row.keySet();
            int j = 0 ;
            for (String key : set) {
                String value = row.get(key);
                XWPFTableCell cell = table.getRow(i).getCell(j);
                cell.setText(value);
                if ("".equals(value) || value == null) {
                    cell.setColor("DCDCDC");
                }
                List<XWPFParagraph> paragraphList = cell.getParagraphs();
                for (XWPFParagraph xwpfParagraph : paragraphList) {
                    xwpfParagraph.setAlignment(ParagraphAlignment.CENTER);
                }
                j++ ;
            }
        }
    }


}
